<template>
    <div class="img-upload" :style="{
                width: width || 'auto',
                height: height || 'auto'
            }" :class="{disabled}">
            <el-upload
            class="upload-demo"
            :action="$uploadUrl"
            ref="upload"
            accept="image/*"
            name="file"
            :style="{
                width: width || 'auto',
                height: height || 'auto'
            }"
            :limit="1"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            :disabled="disabled"
            >
            <slot></slot>
            </el-upload>
    </div>
</template>
<script>
export default {
    name: 'ImgUpload',
    props: {
        disabled: {
            type: Boolean,
            default () {
                return false
            }
        },
        width: {
            type: String,
            default () {
                return ''
            }
        },
        height: {
            type: String,
            default () {
                return ''
            }
        }
    },
    methods: {
        uploadSuccess (e) {
            if (e.code == '0') {
                let url = e.data && e.data.url || ''
                this.$emit('uploadSuccess', url, e.data)
                this.$refs.upload.clearFiles()
            }
            this.$loading(false)
        },
        uploadError () {
            this.$message.error('上传失败')
            this.$emit('uploadError')
            this.$loading(false)
        },
        beforeUpload (file) {
            if (file.size > 250 * 1024)  {
                this.$message.error('上传图片不能超过250KB')
                return false
            }
            this.$loading(true)
        }
    }
}
</script>
<style lang="scss" scoped>
.img-upload {
    display: inline-block;
    overflow: hidden;
    cursor: pointer;
    &.disabled {
        cursor: not-allowed;
        ::v-deep.el-upload {
            cursor: not-allowed;
        }
    }
}
</style>